import json
import os
from flask import Flask, request, jsonify

from main import Director

app = Flask(__name__)


game=Director()
first=True

@app.route('/start', methods=['POST'])
def start():
    global game
    first=True
    game.reset()
    return jsonify({"message": "Game started"}), 200

@app.route('/play', methods=['POST'])
def process_json():
    global game
    global first
    data = request.get_json()
    if not data:
        return jsonify({"error": "Invalid JSON"}), 400
    if first:
        # 将数据写入 JSON 文件
        with open('data.json', 'w') as json_file:
            json.dump(data, json_file)
        # first=False
    player_=[p for p in data['playerStateVos'] if p['playerId']==data['playerId']][0]
    # if player_['impacted']:
    #     os._exit(0)
    dir=game.play(data)
    processed_data = {
        "moveType": dir,
    }
    return jsonify(processed_data), 200


if __name__ == '__main__':
    app.run(port=4000)